<?php
/**
 * Author: yixuan
 * Desc:
 * Time: 2016/7/8 15:13
 */

namespace think\session\driver;

use app\lib\IpLocation;
use SessionHandlerInterface;
use think\Config;
use think\Exception;
use think\Db;

class Mysql implements SessionHandlerInterface
{
    protected $handler = null;
    protected $config = [
        'expire' => 259200,//session有效期 默认3天时间
        'session_prefix' => '',//session_key前缀
        'session_table' => 'yx_sys_session',//session存储的数据表名称 不包含前缀
    ];

    protected $table_name = null;

    public function __construct($config = [])
    {
        //获取数据库配置，将数据库配置更新
        $this->config = array_merge($this->config, ['database' => Config::get('database')], $config);
        $this->table_name = $this->config['session_table'];
    }

    /**
     * 打开session
     * @throws Exception
     */
    public function open($savePath, $sessName)
    {
//        $this->handler = Db::connect($this->config['database'])->name($this->table_name);
        $this->handler = Db::connect($this->config['database']);
        return true;
    }

    /**
     * Desc:关闭session
     * Author: yixuan
     * Time: 2016/7/8 17:58
     * @return true
     */
    public function close()
    {
        $this->gc(ini_get('session.gc_maxlifetime'));
        $this->handler = null;
        return true;
    }

    /**
     * Desc:读取session
     * Author: yixuan
     * Time: 2016/7/8 17:58
     * @param $sessID
     * @return false|string
     */
    public function read($sessID)
    {
        $map['session_id'] = ['eq', $this->config['session_prefix'] . $sessID];
        if ($this->config['expire'] != 0) {
            $map['session_expire'] = ['>=', time()];
        }
//        return $this->handler->where($map)->value('session_data');
        return Db::table($this->table_name)->where($map)->value('session_data');
    }

    /**
     * Desc:写入session
     * Author: yixuan
     * Time: 2016/7/8 17:57
     * @param $sessID
     * @param $sessData
     * @return bool
     */
    public function write($sessID, $sessData)
    {
//        $find_result = $this->handler->where('session_id', $this->config['session_prefix'] . $sessID)->find();
        $find_result = Db::table($this->table_name)->where('session_id', $this->config['session_prefix'] . $sessID)->find();
        //构建存入数据库的数据
        $params = [
            'session_id' => $this->config['session_name'] . $sessID,
            'session_expire' => $this->config['expire'] + time(),
            'session_data' => $sessData,
            'ip' => IpLocation::getip(),
        ];
        if ($find_result) {
//            $result = $this->handler->update($params);
            $result = Db::table($this->table_name)->update($params);
        } else {
//            $result = $this->handler->insert($params);
            $result = Db::table($this->table_name)->insert($params);
        }
        return $result ? true : false;
    }

    /**
     * Desc:删除session
     * Author: yixuan
     * Time: 2016/7/8 17:57
     * @param $sessID
     * @return bool
     */
    public function destroy($sessID)
    {
//        $result = $this->handler->where('session_id', '=', $this->config['session_prefix'] . $sessID)->delete();
        $result = Db::table($this->table_name)->where('session_id', '=', $this->config['session_prefix'] . $sessID)->delete();
        return $result ? true : false;
    }

    /**
     * Desc:gc垃圾回收机制
     * Author: yixuan
     * Time: 2016/7/8 17:54
     * @param $max_lifetime
     * @return bool
     */
    public function gc($max_lifetime)
    {
        if ($this->config['expire'] > 0) {
            $map['session_expire'] = ['lt', time()];
        } else {
            $map['session_expire'] = ['lt', time() - $max_lifetime];
        }
//        $result = $this->handler->where($map)->delete();
        $result = Db::table($this->table_name)->where($map)->delete();
        return $result ? true : false;
    }
}